leaderboardApp.controller("metasCtrl", function($scope, $http, $timeout, notifier, httpPost) {
	$scope.loading = false;
	$scope.message = {title: "", text: "", type: "", visible: false};
	$scope.modalMessage = {title: "", text: "", type: "", visible: false};
	
	$scope.editMetaMode = false;
	$scope.metas = [];
	$scope.addMetaData = {nombre: "", tipo: 0, valor: 0.0, ponderacion: 0, usrName: ""};
	$scope.userNames = [];
	$scope.branch = {id: 0, name: ""};
	$scope.branches = [];
	$scope.productGroups = [];
	$scope.tiposMeta = [{id: 1, name: "Por monto de ventas"}, {id: 2, name: "Por cantidad de ventas"}];
	$scope.tipoMeta = $scope.tiposMeta[0];
	$scope.addToAllUsers = false;
	
	$scope.nombresMetas = ["Neurotropas", "Vitaminas", "Blisters", "Ventas sin Recarga"];
	
	$scope.paginator = new Paginator();
	
	$scope.getUserNames = function() {
		httpPost.send($scope.message, "/Leaderboard/AdminServlet/getUserNames", {}, function(data) {
			if(data.code === 0) {
				$scope.userNames = data.userNames;
				$("#txtUsuario").typeahead({source: $scope.userNames, minChars: 3, max: 10});
			}
		});
	};
	$scope.getUserNames();
	
	$scope.getMetas = function() {
		var params = {};
		params["page"] = $scope.paginator.currentPage;
		params["rowsPerPage"] = $scope.paginator.rowsPerPage;
		params["filter"] = $scope.paginator.filter;
		$scope.loading = true;
		httpPost.send($scope.message, "/Leaderboard/MetasServlet/getMetas", params, function(data) {
			if(data.code === 0) {
				$scope.metas = data.metas;
				$scope.paginator.updateTotal(data.total);
			}
			$scope.loading = false;
		});
	};
	
	$scope.getProductGroups = function() {
		$scope.loading = true;
		httpPost.send($scope.message, "/Leaderboard/GruposProductosServlet/getTodosGruposProductos", {}, function(data) {
			if(data.code === 0) {
				$scope.productGroups = data.productGroups;
				$("#cmbProductos").select2();
			}
			$scope.loading = false;
		});
	};
	
	$scope.getProductGroups();
	
	$scope.addMeta = function() {
		$scope.editMetaMode = false;
		$scope.addMetaData = {nombre: "", tipo: 0, valor: 0.0, ponderacion: 20, usrName: ""};
		$scope.addToAllUsers = false;
		$("#cmbTipo,#cmbNombre").select2();
		$("#dlgAddEditMeta").modal("show");
	};
	
	$scope.editMeta = function(meta) {
		$("#cmbTipo,#cmbNombre").select2();
		$scope.editMetaMode = true;
		$scope.editMetaId = meta.metaId;
		$scope.addToAllUsers = false;
		$scope.loading = true;
		httpPost.send($scope.message, "/Leaderboard/MetasServlet/getMeta", {metaId: meta.metaId}, function(data) {
			if(data.code === 0) {
				$scope.addMetaData = {nombre: data.meta.name, tipo: data.meta.type, valor: data.meta.value, ponderacion: data.meta.weight, usrName: data.meta.userName};
				$scope.productGroups = data.meta.productGroups;
				if(data.meta.type === 1) {
					$scope.tipoMeta = $scope.tiposMeta[0];
				} else {
					$scope.tipoMeta = $scope.tiposMeta[1];
				}
				for(var i=0; i<$scope.branches.length; i++) {
					if(data.meta.branchId === $scope.branches[i].id) {
						$scope.branch = $scope.branches[i];
						break;
					}
				}
				$("#dlgAddEditMeta").modal("show");
				$timeout(function() { $("#cmbNombre,#cmbTipo,#cmbProductos,#cmbSucursal").trigger("change"); }, 0, false);
			}
			$scope.loading = false;
		});
	};
	
	$scope.openMetaDialog = function(opt, meta) {
		if(opt.indexOf("add") >= 0) {
			$scope.addMeta();
		} else {
			$scope.editMeta(meta);
		}
	};
	
	$scope.saveMeta = function() {
		$scope.loading = true;
		var filteredProducts = $.grep($scope.productGroups, function(item) {return item.selected; });
		var productIds = $.map(filteredProducts, function(item) { return item.gPrdId; });
		if($scope.branch == null && $scope.branches.length > 0) {
			$scope.branch = $scope.branches[0];
		}
		
		if($scope.editMetaMode) {
			httpPost.send($scope.modalMessage, "/Leaderboard/MetasServlet/updateMeta", {"metaId": $scope.editMetaId, "nombre": $scope.addMetaData.nombre, "tipo": $scope.tipoMeta.id, "valor": $scope.addMetaData.valor, "ponderacion": $scope.addMetaData.ponderacion, "gPrdIds": productIds.toString(), "addToAllInBranch": $scope.addToAllUsers, "branchId": $scope.branch.id}, function(data) {
				if(data.code === 0) {
					$("#dlgAddEditMeta").modal("hide");
					notifier.notifySuccess($scope.message, "Ok", data.reason);
					$scope.addMetaData = {nombre: "", tipo: 0, valor: 0.0, ponderacion: 0, usrName: ""};
					$scope.getBranchMetas();
				}
				$scope.loading = false;
			});
		} else {
			httpPost.send($scope.modalMessage, "/Leaderboard/MetasServlet/addMeta", {"userName": $scope.addMetaData.usrName.split(" - ")[0], "nombre": $scope.addMetaData.nombre, "tipo": $scope.tipoMeta.id, "valor": $scope.addMetaData.valor, "ponderacion": $scope.addMetaData.ponderacion, "gPrdIds": productIds.toString(), "addToAllInBranch": $scope.addToAllUsers, "branchId": $scope.branch.id}, function(data) {
				if(data.code === 0) {
					$("#dlgAddEditMeta").modal("hide");
					notifier.notifySuccess($scope.message, "Ok", data.reason);
					$scope.addMetaData = {nombre: "", tipo: 0, valor: 0.0, ponderacion: 0, usrName: ""};
					$scope.getBranchMetas();
				}
				$scope.loading = false;
			});
		};
	};
	
	$scope.delMeta = function(metaId) {
		if(confirm("Esta seguro que desea eliminar la meta con ID " + metaId + "?")) {
			$scope.loading = true;
			httpPost.send($scope.message, "/Leaderboard/MetasServlet/delMeta", {"metaId": metaId}, function(data) {
				if(data.code === 0) {
					notifier.notifySuccess($scope.message, "Ok", data.reason);
					$scope.getBranchMetas();
				}
				$scope.loading = false;
			});
		};
	};
	
	$scope.getBranchMetas = function() {
		var params = {};
		params["page"] = $scope.paginator.currentPage;
		params["rowsPerPage"] = $scope.paginator.rowsPerPage;
		params["filter"] = $scope.paginator.filter;
		params["branchId"] = $scope.branch.id;
		$scope.loading = true;
		if($scope.branch.id > 0) {
			httpPost.send($scope.message, "/Leaderboard/MetasServlet/getMetas", params, function(data) {
				if(data.code === 0) {
					$scope.metas = data.metas;
					$scope.paginator.updateTotal(data.total);
				}
				$scope.loading = false;
			});
		} else {
			$scope.getMetas();
		}
	};
	$scope.getBranchMetas();
	
	$scope.getBranches = function() {
		httpPost.send($scope.message, "/Leaderboard/AdminServlet/getBranches", {showAllSelector: "YES", showOwnedOnly: "S"}, function(data) {
			if(data.code === 0) {
				$scope.branches = data.branches;
				$scope.branch = $scope.branches[$scope.branches.length - 1];
				$("#cmbBranches,#cmbSucursal").select2();
				$timeout(function() { $("#cmbNombre,#cmbTipo,#cmbBranches,#cmbSucursal").trigger("change"); $scope.branch = $scope.branches[$scope.branches.length - 1]; }, 0, false);
			}
		});
	};
	$scope.getBranches();
	
	$scope.selectAllPrd = function() {
		$.each($scope.productGroups, function(i, item) { item.selected = true; });
	};
	
	$scope.selectNonePrd = function() {
		$.each($scope.productGroups, function(i, item) { item.selected = false; });
	};
	
	$scope.atLeastOneSelected = function() {
		var filteredArr = $.grep($scope.productGroups, function(elm) { return elm.selected; });
		return filteredArr.length > 0;
	};
	
	/************************************** Funciones de Utilería **************************************/
	
	$scope.hideMessage = function() {
		notifier.hideNotif($scope.message);
		notifier.hideNotif($scope.modalMessage);
	};
	
	/************************************** ##################### **************************************/
});